package com.enation.app.javashop.buyer.api.distribution;

import com.enation.app.javashop.core.base.model.vo.SuccessMessage;
import com.enation.app.javashop.core.distribution.exception.DistributionErrorCode;
import com.enation.app.javashop.core.distribution.exception.DistributionException;
import com.enation.app.javashop.core.distribution.model.dos.DistributionDO;
import com.enation.app.javashop.core.distribution.model.dto.ApplyDistributionDTO;
import com.enation.app.javashop.core.distribution.model.vo.DistributionVO;
import com.enation.app.javashop.core.distribution.model.vo.FansDataVO;
import com.enation.app.javashop.core.distribution.service.DistributionManager;
import com.enation.app.javashop.core.member.model.dos.Member;
import com.enation.app.javashop.core.member.service.MemberManager;
import com.enation.app.javashop.framework.context.UserContext;
import com.enation.app.javashop.framework.database.Page;
import com.enation.app.javashop.framework.security.model.Buyer;
import com.enation.app.javashop.framework.util.DateUtil;
import com.enation.app.javashop.framework.util.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 分销商控制器
 *
 * @author Chopper
 * @version v1.0
 * @Description:
 * @since v7.0
 * 2018/5/23 上午8:34
 */

@RestController
@Api(description = "分销商api")
@RequestMapping("/distribution")
public class DistributionBuyerController {

    protected final Log logger = LogFactory.getLog(this.getClass());
    @Resource
    private DistributionManager distributionManager;
    @Autowired
    private MemberManager memberManager;


    @GetMapping(value = "/lower-list")
    @ApiOperation("获取下级分销商")
    public List<DistributionVO> getLowerDistributorList() {
        Buyer buyer = UserContext.getBuyer();
        if (buyer == null) {
            throw new DistributionException(DistributionErrorCode.E1001.code(), DistributionErrorCode.E1001.des());
        }
        try {
            return this.distributionManager.getLowerDistributorTree(buyer.getUid());
        } catch (Exception e) {
            logger.error("获取下级的分销商列表出错", e);
            throw new DistributionException(DistributionErrorCode.E1000.code(), DistributionErrorCode.E1000.des());
        }
    }

    @ApiOperation("获取推荐我的人")
    @GetMapping(value = "/recommend-me")
    public SuccessMessage recommendMe() {
        Buyer buyer = UserContext.getBuyer();
        if (buyer == null) {
            throw new DistributionException(DistributionErrorCode.E1001.code(), DistributionErrorCode.E1001.des());
        }
        try {
            DistributionDO distributor = this.distributionManager.getDistributorByMemberId(buyer.getUid());
            //对分销商做非空校验
            if (distributor == null) {
                throw new DistributionException(DistributionErrorCode.E1000.code(), DistributionErrorCode.E1000.des());
            }
            return new SuccessMessage(this.distributionManager.getUpMember());
        } catch (Exception e) {
            logger.error("获取下级的分销商列表出错", e);
            throw new DistributionException(DistributionErrorCode.E1000.code(), DistributionErrorCode.E1000.des());
        }
    }


    @PostMapping(value = "/apply")
    @ApiOperation("申请成为分销商")
    public SuccessMessage apply(@RequestBody ApplyDistributionDTO applyDTO) {
        Buyer buyer = UserContext.getBuyer();
        if (buyer == null) {
            throw new DistributionException(DistributionErrorCode.E1001.code(), DistributionErrorCode.E1001.des());
        }

        Member member = memberManager.getModel(buyer.getUid());
        member.setMidentity(applyDTO.getMidentity());
        member.setRealName(applyDTO.getRealName());
        memberManager.edit(member, member.getMemberId());

        DistributionDO distributionDO = distributionManager.getDistributorByMemberId(member.getMemberId());
        if (distributionDO != null && distributionDO.getAuditStatus() == 1 || distributionDO.getAuditStatus() == 2) {
            throw new RuntimeException("你已经申请成为分销团长了");
        }

        // 上级分销
        String lv1InviteCode = applyDTO.getLv1InviteCode();
        distributionDO.setLv1InviteCode(!StringUtil.isEmpty(lv1InviteCode) ? lv1InviteCode : "000001");
        // 邀请码 非空判断
        if(StringUtil.notEmpty(lv1InviteCode)){
            if(!"000001".equals(lv1InviteCode)){
                DistributionDO inviterDistributor = distributionManager.getDistributorByInviteCode(lv1InviteCode);
                if(inviterDistributor == null){
                    throw new RuntimeException("邀请码不正确");
                }
                distributionDO.setLv1CreateTime(DateUtil.getDateline());
                distributionDO.setMemberIdLv1(inviterDistributor.getMemberId());
                distributionDO.setMemberIdLv2(inviterDistributor.getMemberIdLv1());
            }else{
                Integer memberIdLv1 = distributionDO.getMemberIdLv1();
                if(memberIdLv1 != null){
                    DistributionDO lv1DistributionDO = distributionManager.getDistributorByMemberId(memberIdLv1);
                    if(lv1DistributionDO != null && lv1DistributionDO.getAuditStatus() == 2 && lv1DistributionDO.getStatus() == 1){
                        distributionDO.setLv1InviteCode(lv1DistributionDO.getInviteCode());
                        distributionDO.setLv1CreateTime(DateUtil.getDateline());
                        distributionDO.setMemberIdLv2(lv1DistributionDO.getMemberIdLv1());
                    }
                }
            }
        }

        distributionDO.setAuditStatus(1);
        distributionDO.setStatusName("申请中");
        distributionDO.setApplyReason(applyDTO.getApplyReason());
        distributionDO.setBusinessType(applyDTO.getBusinessType());
        distributionManager.edit(distributionDO);
        return new SuccessMessage("申请成功");
    }

    /**
     * 查询邀请人详情
     */
    @ApiOperation(value = "查询邀请人列表")
    @GetMapping("/query_inviter_list")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "member_id", value = "会员id", required = true, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "page_no", value = "页码", required = true, paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "page_size", value = "分页大小", required = true, paramType = "query", dataType = "int"),

    })
    public Page queryInviterList(@ApiIgnore Integer memberId,
                                 @ApiIgnore Integer pageNo, @ApiIgnore Integer pageSize){
        return distributionManager.loadInviterList(memberId, pageNo, pageSize);
    }

    /**
     *  查询下级团长粉丝列表
     */
    @ApiOperation(value = "查询我的粉丝列表")
    @GetMapping("/query_my_fans_list")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "member_id", value = "会员id", required = true, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "page_no", value = "页码", required = true, paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "page_size", value = "分页大小", required = true, paramType = "query", dataType = "int"),

    })
    public Page queryMyFansList(@ApiIgnore Integer memberId, @ApiIgnore Integer pageNo, @ApiIgnore Integer pageSize){
        return  distributionManager.getMyFansList(memberId,pageNo,pageSize);
    }
    /**
     *  查询下级团长
     */
    @ApiOperation(value = "查询下级团长")
    @GetMapping("/query_next_leader_list")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "member_id", value = "会员id", required = true, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "page_no", value = "页码", required = true, paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "page_size", value = "分页大小", required = true, paramType = "query", dataType = "int"),

    })
    public Page queryNextLeaderList(@ApiIgnore Integer memberId, @ApiIgnore Integer pageNo, @ApiIgnore Integer pageSize){
        return  distributionManager.getNextLeaderList(memberId,pageNo,pageSize);
    }

    /**
     *  我的下级列表
     */
    @ApiOperation(value = "我的下级首页")
    @GetMapping("/fans_index")
    public Map<String, Object> fansIndex(){
        Integer memberId = UserContext.getBuyer().getUid();
        return  distributionManager.fansIndex(memberId);
    }

    /**
     *  我的上级首页列表
     */
    @ApiOperation(value = "我的上级首页列表")
    @GetMapping("/superior_index")
    public Map<String, Object> superiorIndex(){
        Integer memberId = UserContext.getBuyer().getUid();
        return  distributionManager.superiorIndex(memberId);
    }

    /**
     *  我的上级团长
     */
    @ApiOperation(value = "我的上级团长")
    @GetMapping("/my_superior_distribution")
    public Map<String, Object> mySuperiorDistribution(){
        Map<String, Object> map = new HashMap<>();
        Integer memberId = UserContext.getBuyer().getUid();
        Member member = distributionManager.getSuperiorLeader(memberId);
        if(member != null){
            DistributionDO distributionDO = distributionManager.getDistributorByMemberId(memberId);
            map.put("member",member);
            map.put("distribution",distributionDO);
        }
        return  map;
    }

    /**
     *  修改上级团长
     */
    @ApiOperation(value = "修改我的上级团长")
    @GetMapping("/update_superior_distribution")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "mobile_or_invitation_code", value = "手机号或邀请码", required = true, paramType = "query", dataType = "int"),
    })
    public SuccessMessage updateSuperiorDistribution(@ApiIgnore String mobileOrInvitationCode){
        Integer memberId = UserContext.getBuyer().getUid();
        distributionManager.updateSuperiorDistribution(memberId,mobileOrInvitationCode);
        return  new SuccessMessage("修改成功！");
    }

    /**
     *  按照类型查询粉丝数据
     */
    @ApiOperation(value = "按照类型查询粉丝数据")
    @GetMapping("/query_fans_data")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Fans_data_key", value = "粉丝留存数据指标key", paramType = "query", dataType = "string"),
            @ApiImplicitParam(name = "page_no", value = "页码", required = true, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "page_size", value = "分页数", required = true, dataType = "int", paramType = "query")
    })
    public Page queryFansDataByType(@RequestParam("Fans_data_key") String Fans_data_key,
                                    @ApiIgnore @NotNull(message = "页码不能为空") Integer pageNo,
                                    @ApiIgnore @NotNull(message = "每页数量不能为空") Integer pageSize){
        Integer memberId = UserContext.getBuyer().getUid();
        Page page = distributionManager.queryFansDataByType(Fans_data_key, memberId, pageNo, pageSize);
        return page;
    }

}
